package com.authine.cloudpivot.web.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.web.api.dao.HCOMaterialsMapper;
import com.authine.cloudpivot.web.api.service.MaterialsService;
import com.authine.cloudpivot.web.api.vo.HCOMaterials;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * ClassName: MaterialsServiceImpl <br/>
 * Description: <br/>
 * date: 2020/9/4 17:40<br/>
 * @author fj<br />
 * @since JDK 1.8
 */
@Service
@Slf4j
public class MaterialsServiceImpl implements MaterialsService {
    @Autowired
    private HCOMaterialsMapper hcoMaterialsMapper;

    @Override
    public HCOMaterials getMaterialNumber(String productKey, String materialProperties) {
        int num = 0;
        HCOMaterials result = new HCOMaterials();
        // 获取当前年份(格式：2020)
        String year = new SimpleDateFormat("yyyy", Locale.CHINESE).format(new Date());
        // 获取当前月份(格式：Jan、Feb)
        String mouth = new SimpleDateFormat("MMM", Locale.ENGLISH).format(new Date());
        // 根据产品名称获取讲课材料信息
        HCOMaterials hcoMaterials = hcoMaterialsMapper.selectMaterialsByProductKey(productKey);
        log.info("last HCOMaterials：{}", JSONObject.toJSONString(hcoMaterials));
        // 材料编号格式：--P-STD-20N04-Valid Until 2022 Jul
        // 该产品有材料信息，产品编号累加
        if (hcoMaterials != null) {
            // 获取最后一条数据单据号生成时的年份，材料编号每年都需要重新开始
            // 单据号格式为Material-2020-0001
            String lastYear = hcoMaterials.getSequenceno().substring(9, 13);
            // 当前年份和最后一条数据年份一致，编号累加，其他情况编号从1开始累加
            if (year.equals(lastYear)) {
                num = hcoMaterials.getNumber().intValue();
            }
        }
        StringBuilder builder = new StringBuilder();
        builder.append(materialProperties);// 推广：P 非推广：NP
        builder.append("-");
        builder.append(productKey);// 产品缩写
        builder.append("-");
        builder.append(year.substring(2));// 获取年份后两位
        builder.append("N");
        builder.append(String.format("%02d", ++num));// 位数不足两位前面补0
        builder.append("-Valid Until ");
        builder.append(Integer.valueOf(year) + 2);// 有效期为两年后
        builder.append(" ");
        builder.append(mouth);
        result.setMaterialnumber(builder.toString());
        result.setNumber(new BigDecimal(num));
        log.info("result：{}", JSONObject.toJSONString(result));
        return result;
    }
}
